<?php
/**
 * 
 * @author Paolo Bertuzzo
 *
 */
namespace Catalog\Controller;

use Utilities\Geolocation\GeolocationService;
use Catalog\Service\StoreService;
use Catalog\Service\BasketService;
use Zend\View\Model\ViewModel;
use Utilities\Session\SessionFacade;

/**
 */
class BasketController extends AbstractGeolocalizedController
{

    /**
     */
    protected $basketService;
    
    /**
     * 
     * @param BasketService $basketService
     * @param GeolocationService $geolocationService
     * @param StoreService $storeService
     */
    public function __construct(BasketService $basketService, GeolocationService $geolocationService, StoreService $storeService)
    {
    	parent::__construct($geolocationService, $storeService);
    	
    	$this->basketService = $basketService;
    }
    
    /**
     */
    public function viewAction() 
    {
        $sessionFacade = new SessionFacade();
        
    	return new ViewModel(array(
    		'basket' => $this->basketService->get(),
    	    'locale' => $sessionFacade->getLocale()
    	));
    }
    
    /**
     */
    public function addAction()
    {
        $productId = (int) $this->params()->fromPost('product_id');
        $quantity = (int) $this->params()->fromPost('quantity');
        
        // Build up attributes array
        $attributes = array();
        
        foreach (array_keys($this->params()->fromPost()) as $parameter)
            if (!strncmp($parameter, 'attribute_', strlen('attribute_')))
            	array_push($attributes, array("attribute_id" => substr($parameter, strlen('attribute_')), "value" => $this->params()->fromPost($parameter)));
        
        $this->basketService->addItem($productId, $quantity, $attributes);

        return $this->redirect()->toRoute('catalog/basket', array('action' => 'view', 'controller' => 'basket'), array(), true);
    }
    
    /**
     */
    public function deleteAction()
    {
        $itemId = (int) $this->params()->fromPost('item_id');
        
        $this->basketService->deleteItem($itemId);
        
        return $this->redirect()->toRoute('catalog/basket', array('action' => 'view', 'controller' => 'basket'), array(), true);
    }
    
}

?>